package team.pikachu.pikachuclient.login;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;

import android.os.AsyncTask;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import team.pikachu.pikachuclient.R;
import team.pikachu.pikachuclient.beans.User;
import team.pikachu.pikachuclient.guide.GuideActivity;
import team.pikachu.pikachuclient.utils.HttpUtils;
import team.pikachu.pikachuclient.utils.IPConstants;
import team.pikachu.pikachuclient.utils.InternetUtils;
import team.pikachu.pikachuclient.utils.LogUtil;

import static team.pikachu.pikachuclient.utils.LogUtil.getSnackbar;


public class LoginActivity extends AppCompatActivity {

    private static final String LOGTAG = LogUtil
            .makeLogTag(LoginActivity.class);

    private static final String FAILED_LOGIN = "";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;
    private SharedPreferences pre;
    // UI references.
    private AutoCompleteTextView mUsernameView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

    @OnClick(R.id.register_button)
    void onRegister() {
        Intent intent = new Intent(this, RegisteredActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);

        // Set up the login form.
        mUsernameView = (AutoCompleteTextView) findViewById(R.id.email);

        mPasswordView = (EditText) findViewById(R.id.password);
        if (mPasswordView.isFocused()){
            mPasswordView.setSelection(mPasswordView.length());
        }
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        getPreference();

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }


    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mUsernameView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String username = mUsernameView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid username
        if (TextUtils.isEmpty(username)) {
            mUsernameView.setError(getString(R.string.error_field_required));
            focusView = mUsernameView;
            cancel = true;
        } else if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_password_required));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }


        if (cancel) {
            focusView.requestFocus();
        } else {
            boolean isOpenNetwork = InternetUtils.isOpenNetwork(LoginActivity.this);
            if (isOpenNetwork) {
//                showProgress(true);
                mAuthTask = new UserLoginTask(username, password);
                mAuthTask.execute((Void) null);
            } else {
                getSnackbar(mLoginFormView, getString(R.string.error_no_network)).show();
            }
        }
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 3;
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }


    /**
     * 异步加载验证用户名和账户是否匹配，如果匹配在SharedPreference中存储用户名和密码
     * 还没有与服务器建立链接
     */
    public class UserLoginTask extends AsyncTask<Void, Void, String> {

        private final String mUsername;
        private final String mPassword;

        public UserLoginTask(String mUsername, String mPassword) {
            this.mUsername = mUsername;
            this.mPassword = mPassword;
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            String loginPath = IPConstants.SIGN_IN + "?userid=" + mUsername + "&password=" + mPassword;
            return HttpUtils.sendPostMethod(loginPath);

        }

        @Override
        protected void onPostExecute(final String success) {
            mAuthTask = null;
            showProgress(false);
            Log.d(LOGTAG, success);
            User user = null;
            if (!success.equals(getString(R.string.request_failed)) && !success.equals("TIMEOUT")) {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    user = mapper.readValue(success, User.class);
                    Log.d(LOGTAG, user.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //保存账号密码以及相关用户信息
                SharedPreferences.Editor editor = pre.edit();
                editor.putBoolean(getString(R.string.pre_checked), true);
                editor.putString(getString(R.string.pre_username), mUsername);
                editor.putString(getString(R.string.pre_password), mPassword);
                editor.putInt(getString(R.string.pre_userid), user.getId());
                editor.putString(getString(R.string.pre_nickname), user.getNickname());
                editor.putString(getString(R.string.pre_phone), user.getPhone());
                editor.putInt(getString(R.string.pre_roleid), user.getRole().getId());
                editor.putString(getString(R.string.pre_rolename), user.getRole().getName());
                editor.putString(getString(R.string.pre_college), user.getCollege());
                editor.putString(getString(R.string.pre_collegenum), user.getCollegenumber());
                editor.putInt(getString(R.string.pre_schoolid), user.getSchool().getId());
                editor.putString(getString(R.string.pre_schoolname), user.getSchool().getName());
                editor.apply();

                //跳转页面
                Intent intent = new Intent(LoginActivity.this, GuideActivity.class);
                startActivity(intent);
                finish();

            } else {
                if (success.equals("TIMEOUT")) {
                    getSnackbar(mLoginFormView, getString(R.string.error_timeout)).show();
                } else {
                    getSnackbar(mLoginFormView, getString(R.string.failed_login)).show();
                }
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }

    }

    /**
     * 如果pre中没有字段，生成一个新的
     */
    private void getPreference() {
        pre = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        if (pre.getBoolean("CHECKED", false)) {
            // 设置默认是记录迷茫状态
            mUsernameView.setText(pre.getString("USER_NAME", ""));
            mPasswordView.setText(pre.getString("PASSWORD", ""));


        }
    }

}
